package com.ssy.lingxi.order.handler.converter;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.order.model.bo.LogisticsAddressBO;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

/**
 *  将支付参数OrderConfigBO，与表中的Jsonb字段进行转换
 * @author ds
 * @date 2022/2/17
 * @version 2.0.0
 */
@Converter(autoApply = true)
public class JpaJsonToLogisticsAddressConverter implements AttributeConverter<LogisticsAddressBO, String> {
    private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    public JpaJsonToLogisticsAddressConverter() {
        OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    @Override
    public String convertToDatabaseColumn(LogisticsAddressBO attribute) {
        try {
            return OBJECT_MAPPER.writeValueAsString(attribute);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.BUSINESS_ERROR,"订单配置参数转换Json错误");
        }
    }

    @Override
    public LogisticsAddressBO convertToEntityAttribute(String dbData) {
        try {
            if(dbData == null) {
                return new LogisticsAddressBO();
            }
            return OBJECT_MAPPER.readValue(dbData, LogisticsAddressBO.class);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.BUSINESS_ERROR,"数据库json字段转换支付参数实体错误");
        }
    }
}
